package io.gitee.sfch.chunmi.auth.session;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.SessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Spring Session配置，由于是单体项目，当前采用本地存储（非Redis共享）
 */
@Configuration
@EnableSpringHttpSession
public class SpringSessionConf {

    /**
     * Cookie策略
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("JSESSIONID");
        serializer.setCookiePath("/");
        // 用正则表达式配置匹配的域名，可以兼容 localhost、127.0.0.1 等各种场景
        serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
        // 最大生命周期，单位是秒，这里定义为 1天
        serializer.setCookieMaxAge(24 * 60 * 60);
        // 不需要base64加密
        serializer.setUseBase64Encoding(false);
        return serializer;
    }

    /**
     * EnableSpringHttpSession 要求的{@link SessionRepository}
     */
    @Bean
    public MapSessionRepository mapSessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }
}
